const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');
const regionRoutes = require('./routes/regionRoutes');
const userRoutes = require('./routes/userRoutes');
const productRoutes = require('./routes/productRoutes');
const db = require('./config/database');
const mysql = require('mysql2');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');

const app = express();

// 中间件
app.use(helmet({
    contentSecurityPolicy: false // 禁用 CSP，允许所有来源
}));
app.use(cors({
    origin: '*', // 允许所有来源
    methods: ['GET', 'POST', 'PUT', 'DELETE'],
    allowedHeaders: ['Content-Type', 'Authorization']
}));
app.use(express.json());
app.use(morgan('dev'));

// 数据库连接配置
const dbConnection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'zZ20021022',
  database: 'supermarket_management',
  charset: 'utf8mb4'
});

// 连接数据库
dbConnection.connect((err) => {
  if (err) {
    console.error('数据库连接失败:', err);
    return;
  }
  console.log('数据库连接成功');
});

// 登录接口
app.post('/api/auth/login', async (req, res) => {
  const { username, password } = req.body;
  
  try {
    const [rows] = await dbConnection.promise().query(
      'SELECT * FROM users WHERE username = ?',
      [username]
    );

    if (rows.length === 0) {
      return res.status(401).json({ message: '用户名或密码错误' });
    }

    const user = rows[0];
    const validPassword = await bcrypt.compare(password, user.password);

    if (!validPassword) {
      return res.status(401).json({ message: '用户名或密码错误' });
    }

    const token = jwt.sign(
      { id: user.id, username: user.username },
      'your_jwt_secret',
      { expiresIn: '24h' }
    );

    res.json({ token });
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取商品列表
app.get('/api/products', authenticateToken, async (req, res) => {
  try {
    const [rows] = await dbConnection.promise().query('SELECT * FROM products');
    res.json(rows);
  } catch (error) {
    res.status(500).json({ message: '获取商品列表失败' });
  }
});

// 添加商品
app.post('/api/products', authenticateToken, async (req, res) => {
  console.log('收到添加商品请求:', req.body);
  const { name, price, stock } = req.body;
  
  // 验证输入
  if (!name || !price || !stock) {
    console.log('缺少必要字段:', { name, price, stock });
    return res.status(400).json({ 
      message: '请提供完整的商品信息',
      details: { name, price, stock }
    });
  }

  try {
    // 转换价格和库存为数字
    const priceNum = parseFloat(price);
    const stockNum = parseInt(stock);

    console.log('转换后的数据:', { name, priceNum, stockNum });

    if (isNaN(priceNum) || priceNum <= 0) {
      return res.status(400).json({ 
        message: '价格必须是大于0的数字' 
      });
    }

    if (isNaN(stockNum) || stockNum < 0) {
      return res.status(400).json({ 
        message: '库存必须是非负整数' 
      });
    }

    // 检查数据库连接
    if (!dbConnection) {
      throw new Error('数据库连接未建立');
    }

    // 插入新商品
    const [result] = await dbConnection.promise().query(
      'INSERT INTO products (name, price, stock) VALUES (?, ?, ?)',
      [name, priceNum, stockNum]
    );

    console.log('插入结果:', result);

    // 返回新创建的商品信息
    const [newProduct] = await dbConnection.promise().query(
      'SELECT * FROM products WHERE id = ?',
      [result.insertId]
    );

    console.log('新创建的商品:', newProduct[0]);

    res.status(201).json(newProduct[0]);
  } catch (error) {
    console.error('添加商品失败:', error);
    // 检查是否是唯一键冲突
    if (error.code === 'ER_DUP_ENTRY') {
      return res.status(400).json({ 
        message: '商品名称已存在' 
      });
    }
    // 检查是否是数据库连接错误
    if (error.code === 'ECONNREFUSED') {
      return res.status(500).json({ 
        message: '数据库连接失败' 
      });
    }
    res.status(500).json({ 
      message: '添加商品失败',
      error: error.message,
      code: error.code
    });
  }
});

// 更新商品
app.put('/api/products/:id', authenticateToken, async (req, res) => {
  const { name, price, stock } = req.body;
  try {
    await dbConnection.promise().query(
      'UPDATE products SET name = ?, price = ?, stock = ? WHERE id = ?',
      [name, price, stock, req.params.id]
    );
    res.json({ message: '更新成功' });
  } catch (error) {
    console.error('更新商品失败:', error);
    res.status(500).json({ message: '更新商品失败' });
  }
});

// 删除商品
app.delete('/api/products/:id', authenticateToken, async (req, res) => {
  try {
    await dbConnection.promise().query('DELETE FROM products WHERE id = ?', [req.params.id]);
    res.json({ message: '删除成功' });
  } catch (error) {
    res.status(500).json({ message: '删除商品失败' });
  }
});

// 获取区域列表
app.get('/api/regions', authenticateToken, async (req, res) => {
  try {
    const [rows] = await dbConnection.promise().query('SELECT * FROM regions');
    res.json(rows);
  } catch (error) {
    console.error('获取区域列表失败:', error);
    res.status(500).json({ message: '获取区域列表失败' });
  }
});

// 添加区域
app.post('/api/regions', authenticateToken, async (req, res) => {
  const { name, code, level, parent_id, manager_id } = req.body;
  
  if (!name || !code || !level) {
    return res.status(400).json({ 
      message: '请提供区域名称、编码和级别' 
    });
  }

  try {
    // 检查编码是否已存在
    const [existing] = await dbConnection.promise().query(
      'SELECT id FROM regions WHERE code = ?',
      [code]
    );

    if (existing.length > 0) {
      return res.status(400).json({ 
        message: '区域编码已存在' 
      });
    }

    // 检查上级区域是否存在
    if (parent_id) {
      const [parent] = await dbConnection.promise().query(
        'SELECT id FROM regions WHERE id = ?',
        [parent_id]
      );

      if (parent.length === 0) {
        return res.status(400).json({ 
          message: '上级区域不存在' 
        });
      }
    }

    // 检查区域经理是否存在
    if (manager_id) {
      const [manager] = await dbConnection.promise().query(
        'SELECT id FROM employees WHERE id = ?',
        [manager_id]
      );

      if (manager.length === 0) {
        return res.status(400).json({ 
          message: '区域经理不存在' 
        });
      }
    }

    const [result] = await dbConnection.promise().query(
      'INSERT INTO regions (name, code, level, parent_id, manager_id) VALUES (?, ?, ?, ?, ?)',
      [name, code, level, parent_id || null, manager_id || null]
    );

    const [newRegion] = await dbConnection.promise().query(
      'SELECT * FROM regions WHERE id = ?',
      [result.insertId]
    );

    res.status(201).json(newRegion[0]);
  } catch (error) {
    console.error('添加区域失败:', error);
    res.status(500).json({ message: '添加区域失败' });
  }
});

// 删除区域
app.delete('/api/regions/:id', authenticateToken, async (req, res) => {
  try {
    await dbConnection.promise().query('DELETE FROM regions WHERE id = ?', [req.params.id]);
    res.json({ message: '删除成功' });
  } catch (error) {
    console.error('删除区域失败:', error);
    res.status(500).json({ message: '删除区域失败' });
  }
});

// 更新区域
app.put('/api/regions/:id', authenticateToken, async (req, res) => {
  const { name, code, level, parent_id, manager_id } = req.body;
  
  if (!name || !code || !level) {
    return res.status(400).json({ 
      message: '请提供区域名称、编码和级别' 
    });
  }

  try {
    // 检查编码是否已被其他区域使用
    const [existing] = await dbConnection.promise().query(
      'SELECT id FROM regions WHERE code = ? AND id != ?',
      [code, req.params.id]
    );

    if (existing.length > 0) {
      return res.status(400).json({ 
        message: '区域编码已被其他区域使用' 
      });
    }

    // 检查上级区域是否存在
    if (parent_id) {
      const [parent] = await dbConnection.promise().query(
        'SELECT id FROM regions WHERE id = ?',
        [parent_id]
      );

      if (parent.length === 0) {
        return res.status(400).json({ 
          message: '上级区域不存在' 
        });
      }
    }

    // 检查区域经理是否存在
    if (manager_id) {
      const [manager] = await dbConnection.promise().query(
        'SELECT id FROM employees WHERE id = ?',
        [manager_id]
      );

      if (manager.length === 0) {
        return res.status(400).json({ 
          message: '区域经理不存在' 
        });
      }
    }

    await dbConnection.promise().query(
      'UPDATE regions SET name = ?, code = ?, level = ?, parent_id = ?, manager_id = ? WHERE id = ?',
      [name, code, level, parent_id || null, manager_id || null, req.params.id]
    );
    res.json({ message: '更新成功' });
  } catch (error) {
    console.error('更新区域失败:', error);
    res.status(500).json({ message: '更新区域失败' });
  }
});

// 更新区域状态
app.put('/api/regions/:id/status', authenticateToken, async (req, res) => {
  const { status } = req.body;
  
  if (!status || !['active', 'inactive'].includes(status)) {
    return res.status(400).json({ 
      message: '无效的状态值' 
    });
  }

  try {
    await dbConnection.promise().query(
      'UPDATE regions SET status = ? WHERE id = ?',
      [status, req.params.id]
    );
    res.json({ message: '状态更新成功' });
  } catch (error) {
    console.error('更新区域状态失败:', error);
    res.status(500).json({ message: '更新区域状态失败' });
  }
});

// 获取门店列表
app.get('/api/stores', authenticateToken, async (req, res) => {
  try {
    const [rows] = await dbConnection.promise().query(`
      SELECT s.*, e.name as manager_name 
      FROM stores s 
      LEFT JOIN employees e ON s.manager_id = e.id
    `);
    res.json(rows);
  } catch (error) {
    console.error('获取门店列表失败:', error);
    res.status(500).json({ message: '获取门店列表失败' });
  }
});

// 添加门店
app.post('/api/stores', authenticateToken, async (req, res) => {
  const { name, address, phone, manager } = req.body;
  
  if (!name || !address) {
    return res.status(400).json({ 
      message: '请提供门店名称和地址' 
    });
  }

  try {
    const [result] = await dbConnection.promise().query(
      'INSERT INTO stores (name, address, phone, manager) VALUES (?, ?, ?, ?)',
      [name, address, phone, manager]
    );

    const [newStore] = await dbConnection.promise().query(
      'SELECT * FROM stores WHERE id = ?',
      [result.insertId]
    );

    res.status(201).json(newStore[0]);
  } catch (error) {
    console.error('添加门店失败:', error);
    res.status(500).json({ message: '添加门店失败' });
  }
});

// 更新门店
app.put('/api/stores/:id', authenticateToken, async (req, res) => {
  const { name, address, phone, manager_id } = req.body;
  
  if (!name || !address) {
    return res.status(400).json({ 
      message: '请提供门店名称和地址' 
    });
  }

  try {
    await dbConnection.promise().query(
      'UPDATE stores SET name = ?, address = ?, phone = ?, manager_id = ? WHERE id = ?',
      [name, address, phone, manager_id || null, req.params.id]
    );
    res.json({ message: '更新成功' });
  } catch (error) {
    console.error('更新门店失败:', error);
    res.status(500).json({ message: '更新门店失败' });
  }
});

// 更新门店状态
app.put('/api/stores/:id/status', authenticateToken, async (req, res) => {
  const { status } = req.body;
  
  if (!status || !['active', 'inactive'].includes(status)) {
    return res.status(400).json({ 
      message: '无效的状态值' 
    });
  }

  try {
    await dbConnection.promise().query(
      'UPDATE stores SET status = ? WHERE id = ?',
      [status, req.params.id]
    );
    res.json({ message: '状态更新成功' });
  } catch (error) {
    console.error('更新门店状态失败:', error);
    res.status(500).json({ message: '更新门店状态失败' });
  }
});

// 获取员工列表
app.get('/api/employees', authenticateToken, async (req, res) => {
  try {
    const [rows] = await dbConnection.promise().query('SELECT * FROM employees');
    res.json(rows);
  } catch (error) {
    console.error('获取员工列表失败:', error);
    res.status(500).json({ message: '获取员工列表失败' });
  }
});

// 添加员工
app.post('/api/employees', authenticateToken, async (req, res) => {
  const { name, phone, position, store_id, hire_date } = req.body;
  
  if (!name || !position) {
    return res.status(400).json({ 
      message: '请提供员工姓名和职位' 
    });
  }

  try {
    const [result] = await dbConnection.promise().query(
      'INSERT INTO employees (name, phone, position, store_id, hire_date) VALUES (?, ?, ?, ?, ?)',
      [name, phone, position, store_id || null, hire_date || null]
    );

    const [newEmployee] = await dbConnection.promise().query(
      'SELECT * FROM employees WHERE id = ?',
      [result.insertId]
    );

    res.status(201).json(newEmployee[0]);
  } catch (error) {
    console.error('添加员工失败:', error);
    res.status(500).json({ message: '添加员工失败' });
  }
});

// 更新员工
app.put('/api/employees/:id', authenticateToken, async (req, res) => {
  const { name, phone, position, store_id, hire_date } = req.body;
  
  if (!name || !position) {
    return res.status(400).json({ 
      message: '请提供员工姓名和职位' 
    });
  }

  try {
    await dbConnection.promise().query(
      'UPDATE employees SET name = ?, phone = ?, position = ?, store_id = ?, hire_date = ? WHERE id = ?',
      [name, phone, position, store_id || null, hire_date || null, req.params.id]
    );
    res.json({ message: '更新成功' });
  } catch (error) {
    console.error('更新员工失败:', error);
    res.status(500).json({ message: '更新员工失败' });
  }
});

// 更新员工状态
app.put('/api/employees/:id/status', authenticateToken, async (req, res) => {
  const { status } = req.body;
  
  if (!status || !['active', 'inactive'].includes(status)) {
    return res.status(400).json({ 
      message: '无效的状态值' 
    });
  }

  try {
    await dbConnection.promise().query(
      'UPDATE employees SET status = ? WHERE id = ?',
      [status, req.params.id]
    );
    res.json({ message: '状态更新成功' });
  } catch (error) {
    console.error('更新员工状态失败:', error);
    res.status(500).json({ message: '更新员工状态失败' });
  }
});

// 获取营销策略列表
app.get('/api/marketing-strategies', authenticateToken, async (req, res) => {
  try {
    const [rows] = await dbConnection.promise().query(`
      SELECT s.*, c.name as category_name 
      FROM marketing_strategies s 
      LEFT JOIN categories c ON s.category_id = c.id
    `);
    res.json(rows);
  } catch (error) {
    console.error('获取营销策略列表失败:', error);
    res.status(500).json({ message: '获取营销策略列表失败' });
  }
});

// 添加营销策略
app.post('/api/marketing-strategies', authenticateToken, async (req, res) => {
  const { name, description, category_id, discount_rate, start_time, end_time, duration, status } = req.body;
  
  if (!name || !category_id || !discount_rate || !start_time || !end_time || !duration) {
    return res.status(400).json({ 
      message: '请提供完整的策略信息' 
    });
  }

  try {
    const [result] = await dbConnection.promise().query(
      'INSERT INTO marketing_strategies (name, description, category_id, discount_rate, start_time, end_time, duration, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
      [name, description, category_id, discount_rate, start_time, end_time, duration, status || 'active']
    );

    const [newStrategy] = await dbConnection.promise().query(
      'SELECT s.*, c.name as category_name FROM marketing_strategies s LEFT JOIN categories c ON s.category_id = c.id WHERE s.id = ?',
      [result.insertId]
    );

    res.status(201).json(newStrategy[0]);
  } catch (error) {
    console.error('添加营销策略失败:', error);
    res.status(500).json({ message: '添加营销策略失败' });
  }
});

// 更新营销策略
app.put('/api/marketing-strategies/:id', authenticateToken, async (req, res) => {
  const { name, description, category_id, discount_rate, start_time, end_time, duration, status } = req.body;
  
  if (!name || !category_id || !discount_rate || !start_time || !end_time || !duration) {
    return res.status(400).json({ 
      message: '请提供完整的策略信息' 
    });
  }

  try {
    await dbConnection.promise().query(
      'UPDATE marketing_strategies SET name = ?, description = ?, category_id = ?, discount_rate = ?, start_time = ?, end_time = ?, duration = ?, status = ? WHERE id = ?',
      [name, description, category_id, discount_rate, start_time, end_time, duration, status, req.params.id]
    );
    res.json({ message: '更新成功' });
  } catch (error) {
    console.error('更新营销策略失败:', error);
    res.status(500).json({ message: '更新营销策略失败' });
  }
});

// 更新营销策略状态
app.put('/api/marketing-strategies/:id/status', authenticateToken, async (req, res) => {
  const { status } = req.body;
  
  if (!status || !['active', 'inactive'].includes(status)) {
    return res.status(400).json({ 
      message: '无效的状态值' 
    });
  }

  try {
    await dbConnection.promise().query(
      'UPDATE marketing_strategies SET status = ? WHERE id = ?',
      [status, req.params.id]
    );
    res.json({ message: '状态更新成功' });
  } catch (error) {
    console.error('更新营销策略状态失败:', error);
    res.status(500).json({ message: '更新营销策略状态失败' });
  }
});

// 获取商品品类列表
app.get('/api/categories', authenticateToken, async (req, res) => {
  try {
    const [rows] = await dbConnection.promise().query('SELECT * FROM categories');
    res.json(rows);
  } catch (error) {
    console.error('获取商品品类列表失败:', error);
    res.status(500).json({ message: '获取商品品类列表失败' });
  }
});

// 添加商品品类
app.post('/api/categories', authenticateToken, async (req, res) => {
  const { name, code, parent_id } = req.body;
  
  if (!name || !code) {
    return res.status(400).json({ 
      message: '请提供品类名称和编码' 
    });
  }

  try {
    const [result] = await dbConnection.promise().query(
      'INSERT INTO categories (name, code, parent_id) VALUES (?, ?, ?)',
      [name, code, parent_id || null]
    );

    const [newCategory] = await dbConnection.promise().query(
      'SELECT * FROM categories WHERE id = ?',
      [result.insertId]
    );

    res.status(201).json(newCategory[0]);
  } catch (error) {
    console.error('添加商品品类失败:', error);
    res.status(500).json({ message: '添加商品品类失败' });
  }
});

// 更新商品品类
app.put('/api/categories/:id', authenticateToken, async (req, res) => {
  const { name, code, parent_id } = req.body;
  
  if (!name || !code) {
    return res.status(400).json({ 
      message: '请提供品类名称和编码' 
    });
  }

  try {
    await dbConnection.promise().query(
      'UPDATE categories SET name = ?, code = ?, parent_id = ? WHERE id = ?',
      [name, code, parent_id || null, req.params.id]
    );
    res.json({ message: '更新成功' });
  } catch (error) {
    console.error('更新商品品类失败:', error);
    res.status(500).json({ message: '更新商品品类失败' });
  }
});

// 更新商品品类状态
app.put('/api/categories/:id/status', authenticateToken, async (req, res) => {
  const { status } = req.body;
  
  if (!status || !['active', 'inactive'].includes(status)) {
    return res.status(400).json({ 
      message: '无效的状态值' 
    });
  }

  try {
    await dbConnection.promise().query(
      'UPDATE categories SET status = ? WHERE id = ?',
      [status, req.params.id]
    );
    res.json({ message: '状态更新成功' });
  } catch (error) {
    console.error('更新商品品类状态失败:', error);
    res.status(500).json({ message: '更新商品品类状态失败' });
  }
});

// Token 验证中间件
function authenticateToken(req, res, next) {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (!token) {
    return res.status(401).json({ message: '未提供认证令牌' });
  }

  jwt.verify(token, 'your_jwt_secret', (err, user) => {
    if (err) {
      return res.status(403).json({ message: '无效的认证令牌' });
    }
    req.user = user;
    next();
  });
}

// 路由
app.use('/api/regions', regionRoutes);
app.use('/api/users', userRoutes);
app.use('/api/products', productRoutes);

// 错误处理中间件
app.use((err, req, res, next) => {
    console.error('错误详情:', err);
    res.status(500).json({
        message: '服务器内部错误',
        error: process.env.NODE_ENV === 'development' ? err.message : undefined
    });
});

// 启动服务器
const PORT = 3001;  // 固定使用 3001 端口
app.listen(PORT, async () => {
    console.log(`后端服务器运行在端口 ${PORT}`);
    await dbConnection.promise().query('SELECT 1');
});